package dy.app.util;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import dy.app.enums.BizCodeEnum;
import dy.app.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公共工具类
 * Author: cKnight
 * Date: 2024/6/9
 */
@Slf4j
public class CommonUtils {


    /**
     * 校验必填项
     * @param args
     */
    public static void checkArgs(Object... args){
        for (Object item : args) {
            if (item instanceof String){
                if (StringUtils.isBlank((String) item)){
                    throw new BizException(BizCodeEnum.SYS_ARGS_ERROR);
                }
            }else if (Objects.isNull(item)){
                throw new BizException(BizCodeEnum.SYS_ARGS_ERROR);
            }
        }
    }

    /**
     * 响应json数据给前端
     *
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {

        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSONObject.toJSONString(obj));
            response.flushBuffer();

        } catch (IOException e) {
            log.warn("响应json数据给前端异常:{}", e.toString());
        }
    }

    /**
     * 转换url
     *
     * @param url
     * @param params
     * @return
     */
    public static String transUrl(String url, Map<String, Object> params) {
        if (CollectionUtils.isEmpty(params)){
            return url;
        }
        String transParams = params.entrySet().stream()
                .map(obj -> obj.getKey() + "=" + obj.getValue().toString())
                .collect(Collectors.joining("&"));
        url = url + "?" + transParams;
        return url;
    }
}
